package org.tinygame.herostory.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.BroadCaster;
import org.tinygame.herostory.mode.User;
import org.tinygame.herostory.mode.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * 用户功击指令处理
 */
public class UserAttkCmdHandler implements ICmdHandler<GameMsgProtocol.UserAttkCmd> {

    @Override
    public void handler(ChannelHandlerContext ctx, GameMsgProtocol.UserAttkCmd cmd) {
        if(null == ctx || null == cmd){
            return;
        }

        //获取攻击者ID
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if(null == userId){
            return;
        }

        //获取被攻击者ID
        int targetUserId = cmd.getTargetUserId();

        //功击处理
        GameMsgProtocol.UserAttkResult.Builder resultBuilder = GameMsgProtocol.UserAttkResult.newBuilder();
        resultBuilder.setAttkUserId(userId);//功击者ID
        resultBuilder.setTargetUserId(targetUserId);//被攻击者ID

        GameMsgProtocol.UserAttkResult newResult = resultBuilder.build();
        BroadCaster.broadCaster(newResult);//广播

        //获取被功击用户
        User targetUser = UserManager.getUserById(targetUserId);

        if(null == targetUser){
            return;
        }

        int hp = 10;//默认打出10点伤害
        targetUser.setHp(targetUser.getHp() - hp);

        //广播减血消息
        broadCastSubtractHp(targetUserId,hp);

        if(targetUser.getHp() <= 0){
            //广播死亡消息
            broadCastDie(targetUserId);
        }

    }

    /**
     * 广播减血消息
     * @param targetUserId 目标用户ID
     * @param subtractHp 减血量
     */
    private void broadCastSubtractHp(int targetUserId,int subtractHp){
        //规避不合法消息处理
        if(targetUserId <= 0 || subtractHp <= 0){
            return;
        }
        //掉血处理 - 默认10点血
        GameMsgProtocol.UserSubtractHpResult.Builder resultBuilder = GameMsgProtocol.UserSubtractHpResult.newBuilder();
        resultBuilder.setSubtractHp(10);
        resultBuilder.setTargetUserId(targetUserId);//掉血者ID

        GameMsgProtocol.UserSubtractHpResult result = resultBuilder.build();
        BroadCaster.broadCaster(result);
    }

    /**
     * 广播死亡消息
     * @param targetUserId 死亡用户ID
     */
    private void broadCastDie(int targetUserId){

        if(targetUserId <= 0){
            return;
        }

        GameMsgProtocol.UserDieResult.Builder resultBuilder = GameMsgProtocol.UserDieResult.newBuilder();
        resultBuilder.setTargetUserId(targetUserId);

        GameMsgProtocol.UserDieResult newResult = resultBuilder.build();
        BroadCaster.broadCaster(newResult);
    }
}
